package com.pat.service;

import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class ClientUtil {

	public static JSONObject get(final String url) {

		JSONObject jsonObject = null;

		try {
			Client client = Client.create();

			WebResource webResource = client.resource(url);

			ClientResponse response = webResource.accept("application/json")
					.get(ClientResponse.class);

			if (response.getStatus() != 200) {
				throw new RuntimeException("Failed : HTTP error code : "
						+ response.getStatus());
			}

			jsonObject = new JSONObject(response.getEntity(String.class));

		} catch (JSONException e) {
			e.printStackTrace();
		}
		return jsonObject;
	}

	public static String post(final String url, final JSONObject json) {
		String output = "";

		Client client = Client.create();

		WebResource webResource = client.resource(url);

		ClientResponse response = webResource.type("application/json").post(
				ClientResponse.class, json.toString());

		if (response.getStatus() != 201) {
			throw new RuntimeException("Failed : HTTP error code : "
					+ response.getStatus());
		}


		output = response.getEntity(String.class);

		return output;

	}

	public static String delete(String url) {
		String output = "";

		Client client = Client.create();

		WebResource webResource = client.resource(url);

		ClientResponse response = webResource.type("application/json").delete(
				ClientResponse.class);

		if (response.getStatus() != 200) {
			throw new RuntimeException("Failed : HTTP error code : "
					+ response.getStatus());
			
		}

		output = response.getEntity(String.class);

		return output;
	}
}
